﻿using PlutoStudio.Net.Processors;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;

namespace PlutoStudio.Net.Processors.Configuration
{
    internal class ProcessorConfigurationManager
    {
        public string ConfigName { get; set; }
        private System.IO.FileSystemWatcher watcher;
        internal ProcessorConfigurationManager(string configName,MessageProcessorFactory factory)
        {
            this.ConfigName = configName;
            watcher = new System.IO.FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, configName);
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Changed += (o, e) =>
            {
                config = null;
                factory.InitProcessor();
            };
            watcher.EnableRaisingEvents = true; ;
        }
        private  System.Configuration.Configuration config;

        public  System.Configuration.Configuration Configuration
        {
            get
            {

                return config ?? (config = GetConfig());
            }
        }

        private  System.Configuration.Configuration GetConfig()
        {
            var file = GetPath();
            var map = new ExeConfigurationFileMap { ExeConfigFilename = file };
            return System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
        }

        private  string GetPath()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var file = System.IO.Path.Combine(path,ConfigName );
            return file;
        }

        public  ProcessorSection Processeor
        {
            get { return Configuration.GetSection("processors") as ProcessorSection; }
        }

    }
}
